<?php

class Feed extends Controller {
	
	var $allowed_formats = array('rss', 'atom', 'json');
	
	function Feed() 
	{
		parent::Controller();   
		
		$this->load->library('ifanboy');				
	}
	
	function generate($user = null, $type = 'rss') {
		
		if (empty($user)) show_error('no user name given');
		
		if (!in_array($type, $this->allowed_formats))
			show_error("'" . $type . '" is not a supported feed format');
		
		if ($type == 'json') {
			$this->json($user);
			return;
		}	
			
		require_once('Zend/Feed.php');
		
		$comics = $this->ifanboy->pull_list($user);
		
		$data = array(
			'title' => 'ifanboy.com user feed - ' . $user,
			'link' => 'http://www.example.com',
			'description' => 'ifanboy comics pulls for '. $user,
			'language' => 'en-us',
			'charset' => 'utf-8',
		);
		
		foreach ($comics as $comic) {
			$data['entries'][] = array(
				'title' => $comic['title'],
				'link' => $comic['url'],
				'description' => $comic['summary'],
				//'lastUpdate' => '',
				'enclosure' => array(
					array(
						'url' => $comic['img'],
	                    'type' => 'image/jpg',
	                    //'length' => 'length of the linked content in octets'
	                ),
				),
			);
		}
		
		$feed = Zend_Feed::importArray($data, $type);
		
		assert($feed instanceof Zend_Feed_Abstract);
		
		print $feed->saveXML();
		
		$feed->send();
	}
	
	private function json($user = null) {
		
		if (empty($user)) show_error('no user name given');
		
		$comics = $this->ifanboy->pull_list($user);
		
		// json headers
		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');
		
		// output raw json 
		echo json_encode($comics);
		
	}
}